﻿using Microsoft.SharePoint.Client;
using Futajma.MigrationStudio.SharePointPersistance;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Futajma.MigrationStudio.SharePointPersistance.Dialog
{

    public partial class ProjectSelectorDialog : System.Windows.Forms.Form
    {
        [ObfuscationAttribute(Exclude = true, ApplyToMembers = true)]
        internal class ComboxItem
        {
            public string LoginName { get; set; }
            public string Text { get; set; }
        }

        public ProjectSelectorDialog()
            : base()
        {
            InitializeComponent();
            ReturnValue = new ReturnValue();
            InitListView();
        }

        public ReturnValue ReturnValue { get; private set; }

        void InitListView()
        {
            listMigrationItems.Columns.Add("Name", 200, HorizontalAlignment.Left);
            listMigrationItems.Columns.Add("Status", 80, HorizontalAlignment.Left);
            listMigrationItems.Columns.Add("Coordinator", 88, HorizontalAlignment.Left);
            listMigrationItems.Columns.Add("Last Modified", 88, HorizontalAlignment.Left);

            SharePoint2010Persistence pers = new SharePoint2010Persistence();
            //bool isUserInMigrationTeam = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), WindowsIdentity.GetCurrent().Name);
            bool isUserInMigrationTeam = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), CredentialManager.ToString());

            if (isUserInMigrationTeam)
            {
                LoadFCComboBox();
                cbxFCoordinators.Visible = true;
            }

            LoadProjects(isUserInMigrationTeam);
           
        }

      

        private void LoadFCComboBox()
        {
            //SharePoint2010Persistence pers = new SharePoint2010Persistence();

            var users = SharePoint2010Persistence.GetAllUsersOfGroup(int.Parse(Settings.MigrationResponsibleGroupId));

            cbxFCoordinators.Items.Clear();

            cbxFCoordinators.Items.Add("Please select");
            cbxFCoordinators.SelectedIndex = 0;

            var userList = users.ToList();

            var data = userList.OrderBy(u => u.Title).Select(user => new ComboxItem()
            {
                LoginName = user.LoginName,
                Text = user.Title
            }).ToList();

            cbxFCoordinators.ValueMember = "LoginName";
            cbxFCoordinators.DisplayMember = "Text";
            //cbxFCoordinators.DataSource = data;

            foreach (var user in data)
            {
                cbxFCoordinators.Items.Add(user);
            }
        }

        private void LoadProjects(bool isUserInMigrationTeam)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                ReturnValue.SelectedSharePointItemId = -1;
                listMigrationItems.Items.Clear();
                SharePoint2010Persistence pers = new SharePoint2010Persistence();

                ListItemCollection items = null;

                if (isUserInMigrationTeam && cbxFCoordinators.SelectedIndex >= 1)
                {
                    items = pers.GetImportableMigrationRecords(((ComboxItem)cbxFCoordinators.SelectedItem).LoginName, true);
                }
                else
                {
                    items = pers.GetImportableMigrationRecords(CredentialManager.ToString(), false);
                }

                foreach (ListItem item in items)
                {
                    var lookupVal = "";

                    if (item[Settings.MigrationRecordStatusFieldname] as FieldLookupValue != null)
                    {
                        var fl = (FieldLookupValue)item[Settings.MigrationRecordStatusFieldname];
                        lookupVal = fl.LookupValue;
                    }
                    else
                    {
                        lookupVal = item[Settings.MigrationRecordStatusFieldname].ToString();
                    }

                    ListViewItem lwItem = new ListViewItem(new[] { item.DisplayName, lookupVal, ((FieldUserValue)item[Settings.MigrationResponsibleFieldname]).LookupValue, item["Modified"].ToString() });
                    lwItem.Tag = item.Id;
                    listMigrationItems.Items.Add(lwItem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public ReturnValue OpenDialog()
        {
            ReturnValue.DialogResult = this.ShowDialog();

            return ReturnValue;
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            SharePoint2010Persistence pers = new SharePoint2010Persistence();
            //bool isUserInMigrationTeam = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), WindowsIdentity.GetCurrent().Name);//CredentialManager.ToString());

            bool isUserInMigrationTeam = pers.EnsureUserInGroup(int.Parse(Settings.MigrationTeamGroupId), CredentialManager.ToString());

            LoadProjects(isUserInMigrationTeam);

        }

        private void listMigrationItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listMigrationItems.SelectedItems.Count > 0)
            {
                btnSelect.Enabled = true;
                if (listMigrationItems.SelectedItems.Count > 0)
                {
                    ReturnValue.SelectedSharePointItemId = (int)listMigrationItems.SelectedItems[0].Tag;
                    ReturnValue.ProjectName = listMigrationItems.SelectedItems[0].SubItems[0].Text;
                }
            }
            else
            {
                btnSelect.Enabled = false;
            }
        }
    }
}
